//
//  CallAcceptTipView.swift
//  ZEGOCallDemo
//
//  Created by zego on 2022/1/12.
//

import UIKit
import Kingfisher
import Reusable

protocol CallAcceptTipViewDelegate: AnyObject {
    //    func tipViewDeclineCall(_ userInfo: UserInfo, callType: CallType)
    //    func tipViewAcceptCall(_ userInfo: UserInfo, callType: CallType)
    //    func tipViewDidClik(_ userInfo: UserInfo, callType: CallType)
}

class ZegoCallInvitationDialog: UIView {
    
    @IBOutlet weak var userNameLabel: UILabel!
    @IBOutlet weak var messageLabel: UILabel!
    @IBOutlet weak var acceptButton: UIButton!
    @IBOutlet weak var refuseButton: UIButton!
    
    
    
    @IBOutlet weak var headLabel: UILabel! {
        didSet {
            headLabel.layer.masksToBounds = true
            headLabel.layer.cornerRadius = 21
            headLabel.textAlignment = .center
        }
    }
    
    lazy var userAvatarImage: UIImageView = {
        let imageView: UIImageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.layer.cornerRadius = 21;
        return imageView
    }()
    
    weak var delegate: CallAcceptTipViewDelegate?
    //    static var showDeclineButton: Bool = true
    private var invitationData: ZegoCallInvitationData? {
        didSet {
            //            self.acceptButton.inviterID = invitationData?.inviter?.userID
            //            self.refuseButton.inviterID = invitationData?.inviter?.userID
            //            let refuseData: [String : AnyObject] = [
            //                "reason": "decline" as AnyObject,
            //                "invitationID": invitationData?.invitationID as AnyObject
            //            ]
            //            self.refuseButton.data = refuseData.jsonString
            if let uRl = URL(string: invitationData?.inviter?.userAvatar ?? "") {
                // 显示来电人的头像
                self.userAvatarImage.kf.setImage(with: uRl)
            }
        }
    }
    
    private var type: ZegoInvitationType = .voiceCall
    
    
    open override func awakeFromNib() {
        super.awakeFromNib()
        let tapClick: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(viewTap))
        self.addGestureRecognizer(tapClick)
        userAvatarImage.frame = self.headLabel.frame
        addSubview(userAvatarImage)
        
        acceptButton.addTarget(self, action: #selector(onAcceptInvitationAction), for: .touchUpInside)
        refuseButton.addTarget(self, action: #selector(onRefuseInvitationAction), for: .touchUpInside)
        
        //        acceptButton.remove(<#T##target: Any?##Any?#>, action: <#T##Selector#>)
        
    }
    
    @discardableResult
    public static func show(_ callInvitationData: ZegoCallInvitationData) -> ZegoCallInvitationDialog {
        return showTipView(callInvitationData)
    }
    
    private static func showTipView(_ callInvitationData: ZegoCallInvitationData) -> ZegoCallInvitationDialog {
        let tipView: ZegoCallInvitationDialog = UINib(nibName: "ZegoCallInvitationDialog", bundle: Bundle(for: ZegoCallInvitationData.self)).instantiate(withOwner: nil, options: nil).first as! ZegoCallInvitationDialog
        let y = KeyWindow().safeAreaInsets.top
        tipView.frame = CGRect.init(x: 8, y: y + 8, width: UIScreen.main.bounds.size.width - 16, height: 80)
        tipView.invitationData = callInvitationData
        tipView.layer.masksToBounds = true
        tipView.layer.cornerRadius = 8
        tipView.type = callInvitationData.type
        tipView.setHeadUserName(callInvitationData.inviter?.userName)
        tipView.userNameLabel.text = callInvitationData.inviter?.userName
        tipView.refuseButton.isHidden = !(ZegoUIKitPrebuiltCallInvitationService.shared.config?.showDeclineButton ?? true)
        
        // 有头像显示头像,没有头像显示名字
        if callInvitationData.userAvatar?.count ?? 0 > 0 {
            tipView.userAvatarImage.isHidden = false
            tipView.headLabel.isHidden = true
            
        } else {
            tipView.headLabel.isHidden = false
            tipView.userAvatarImage.isHidden = true
        }
        
        let innerText: ZegoTranslationText? = ZegoUIKitPrebuiltCallInvitationService.shared.config?.translationText
        switch callInvitationData.type {
        case .voiceCall:
            //            tipView.messageLabel.text = callInvitationData.invitees?.count ?? 0 > 1 ? "Group voice call" : "Voice call"
            tipView.messageLabel.text = callInvitationData.invitees?.count ?? 0 > 1 ? innerText?.incomingGroupVoiceCallDialogMessage : innerText?.incomingVoiceCallDialogMessage
            tipView.userNameLabel.text = callInvitationData.invitees?.count ?? 0 > 1 ? String(format: innerText?.incomingGroupVoiceCallDialogTitle ?? "%@", callInvitationData.inviter?.userName ?? "") : String(format: innerText?.incomingVoiceCallDialogTitle ?? "%@", callInvitationData.inviter?.userName ?? "")
            // tipView.acceptButton.icon = ZegoUIKitCallIconSetType.call_accept_icon.load()
            
            tipView.acceptButton.setImage(ZegoUIKitCallIconSetType.call_accept_icon.load(), for: .normal)
            
        case .videoCall:
            tipView.messageLabel.text = callInvitationData.invitees?.count ?? 0 > 1 ? innerText?.incomingGroupVideoCallDialogMessage : innerText?.incomingVideoCallDialogMessage
            tipView.userNameLabel.text = callInvitationData.invitees?.count ?? 0 > 1 ? String(format: innerText?.incomingGroupVideoCallDialogTitle ?? "%@", callInvitationData.inviter?.userName ?? "") : String(format: innerText?.incomingVideoCallDialogTitle ?? "%@", callInvitationData.inviter?.userName ?? "")
            // tipView.acceptButton.icon  = ZegoUIKitCallIconSetType.call_video_icon.load()
            
            tipView.acceptButton.setImage(ZegoUIKitCallIconSetType.call_video_icon.load(), for: .normal)
        }
        tipView.showTip()
        return tipView
    }
    
    private func setHeadUserName(_ userName: String?) {
        guard let userName = userName else { return }
        if userName.count > 0 {
            let firstStr: String = String(userName[userName.startIndex])
            self.headLabel.text = firstStr
        }
    }
    
    public static func hide() {
        DispatchQueue.main.async {
            for subview in KeyWindow().subviews {
                if subview is ZegoCallInvitationDialog {
                    let view: ZegoCallInvitationDialog = subview as! ZegoCallInvitationDialog
                    view.removeFromSuperview()
                }
            }
        }
    }
    
    private func showTip()  {
        KeyWindow().addSubview(self)
    }
    
    @objc func viewTap() {
        // 点击通知，打开视频通话页面
        let vc = UINib.init(nibName: "ZegoUIKitPrebuiltCallWaitingVC", bundle: Bundle(for: ZegoUIKitPrebuiltCallWaitingVC.self)).instantiate(withOwner: nil, options: nil).first as! ZegoUIKitPrebuiltCallWaitingVC
        vc.isInviter = false
        vc.callInvitationData = self.invitationData
        vc.modalPresentationStyle = .fullScreen
        currentViewController()?.present(vc, animated: true, completion: nil)
        vc.showDeclineButton = ZegoUIKitPrebuiltCallInvitationService.shared.config?.showDeclineButton ?? true
        ZegoCallInvitationDialog.hide()
    }
    
}


extension ZegoCallInvitationDialog {
    @objc func onAcceptInvitationAction() {
        xLog("同意邀请视频通话")
        if UserProfile.country > 0 {
            // 我是俄罗斯的,不需要判断积分和身份
            receivedInvitation()
            return
        }
        
        guard let inviterId = invitationData?.inviter?.userID else {
            return
        }
        xLog("邀请者 id: \(inviterId)")
        
        let group = DispatchGroup()
        let queue = DispatchQueue(label: "inviterGCD", attributes: .concurrent)
        
        var inviterUserModel: UserModel?
        var myUserModel: UserModel?
        
        group.enter()
        queue.async(group: group) {
            // 获取邀请者信息
            MineMainViewModel.loadUserInfo(inviterId) { userModel in
                inviterUserModel = userModel
                group.leave()
            }
        }
        
        group.enter()
        queue.async(group: group) {
            MineMainViewModel.loadUserInfo(String(UserProfile.userId)) { userModel in
                myUserModel = userModel
                group.leave()
            }
        }
        
        // 当所有任务完成时通知
        group.notify(queue: DispatchQueue.main) { [weak self] in
            xLog("所有任务完成")
            /**
             接听
            
             1.接听者是中国用户,拨打者是海外用户,接听者不是翻译
             接听者积分 <= 0  不能接听,提示积分充值 ✅
             接听者积分 > 0 可以接听 ✅
             
             2.接听者是中国用户,拨打者是海外用户,接听者是翻译
             可以接听
             
             3.接听者是中国用户,拨打者是中国用户
             接听者积分 <= 0  不能接听,提示积分充值
             接听者积分 > 0 可以接听
             
             */
            
            if inviterUserModel?.country == 0 {
                // 我是中国人, 中国给中国打, 接不拦
                self?.receivedInvitation()
                return
            }
            
            // 我是翻译, 接不拦
            if IdentityType(rawValue: UserProfile.identityId) == .interpreter {
                self?.receivedInvitation()
                return
            }
            
            // 我不是翻译
            if (myUserModel?.score ?? 0) > 0 {
                // 积分充足,可以接听
                self?.receivedInvitation()
                
            } else {
                // 没有积分,不许接听,去充值页面, 拒绝通话
                self?.refuseInvitation()
                
                let url = SystemEnvManager.shared.forwarderUrl + "/pages/vip/scorePoint?" + H5UrlManager.urlParameter()
                let vc = BaseWebViewController(url: url, isNavBarHide: true)
                // 只有中国人会收到这个提示
                vc.message = "当前积分不足，无法接起国际通话。"
                currentController?.push(vc)
            }
        }
    }
    
    @objc func onRefuseInvitationAction() {
        refuseInvitation()
    }
    
    
    func receivedInvitation() {
        guard let invitationData = invitationData else {
            return
        }
        
        var normalConfig = ZegoUIKitPrebuiltCallConfig.oneOnOneVoiceCall()
        if invitationData.invitees?.count ?? 0 > 1 {
            //group call
            //            nomalConfig = ZegoUIKitPrebuiltCallConfig(invitationData.type == .videoCall ? .groupVideoCall : .groupVoiceCall)
            normalConfig = invitationData.type == .videoCall ? ZegoUIKitPrebuiltCallConfig.groupVideoCall() : ZegoUIKitPrebuiltCallConfig.groupVoiceCall()
        } else {
            //one on one call
            //            nomalConfig = ZegoUIKitPrebuiltCallConfig(invitationData.type == .videoCall ? .oneOnOneVideoCall : .oneOnOneVoiceCall)
            normalConfig =  invitationData.type == .videoCall ? ZegoUIKitPrebuiltCallConfig.oneOnOneVideoCall() : ZegoUIKitPrebuiltCallConfig.oneOnOneVoiceCall()
        }
        let config = ZegoUIKitPrebuiltCallInvitationService.shared.delegate?.requireConfig(invitationData) ?? normalConfig
        let callVC: ZegoUIKitPrebuiltCallVC = ZegoUIKitPrebuiltCallVC.init(invitationData, config: config)
        callVC.modalPresentationStyle = .fullScreen
        callVC.delegate = ZegoUIKitPrebuiltCallInvitationService.shared.help
        currentViewController()?.present(callVC, animated: true, completion: nil)
        ZegoCallInvitationDialog.hide()
        ZegoUIKitPrebuiltCallInvitationService.shared.callVC = callVC
        ZegoUIKitPrebuiltCallInvitationService.shared.delegate?.onIncomingCallAcceptButtonPressed?()
        ZegoCallAudioPlayerTool.stopPlay()
        ZegoUIKitPrebuiltCallInvitationService.shared.state = .accept
        //        ZegoUIKitPrebuiltCallInvitationService.shared.invitationData = nil
        ZegoUIKitSignalingPluginImpl.shared.acceptInvitation(invitationData.inviter?.userID ?? "", data: nil, callback: nil)
        
    }
    
    /// 拒绝邀请
    public func refuseInvitation() {
        
        ZegoCallAudioPlayerTool.stopPlay()
        ZegoUIKitPrebuiltCallInvitationService.shared.delegate?.onIncomingCallDeclineButtonPressed?()
        ZegoUIKitPrebuiltCallInvitationService.shared.invitationData = nil
        ZegoUIKitPrebuiltCallInvitationService.shared.callID = nil
        ZegoCallInvitationDialog.hide()
        ZegoUIKitPrebuiltCallInvitationService.shared.state = .normal
        
        guard let inviterID = invitationData?.inviter?.userID else { return }
        
        ZegoUIKitSignalingPluginImpl.shared.refuseInvitation(inviterID, data: [
            "reason": "decline" as AnyObject,
            "invitationID": invitationData?.invitationID as AnyObject
        ].jsonString)
    }
}








//extension ZegoCallInvitationDialog: ZegoAcceptInvitationButtonDelegate {
//    public func onAcceptInvitationButtonClick() {
//        guard let invitationData = invitationData else {
//            return
//        }
//        var normalConfig = ZegoUIKitPrebuiltCallConfig.oneOnOneVoiceCall()
//        if invitationData.invitees?.count ?? 0 > 1 {
//            //group call
////            nomalConfig = ZegoUIKitPrebuiltCallConfig(invitationData.type == .videoCall ? .groupVideoCall : .groupVoiceCall)
//            normalConfig = invitationData.type == .videoCall ? ZegoUIKitPrebuiltCallConfig.groupVideoCall() : ZegoUIKitPrebuiltCallConfig.groupVoiceCall()
//        } else {
//            //one on one call
////            nomalConfig = ZegoUIKitPrebuiltCallConfig(invitationData.type == .videoCall ? .oneOnOneVideoCall : .oneOnOneVoiceCall)
//            normalConfig =  invitationData.type == .videoCall ? ZegoUIKitPrebuiltCallConfig.oneOnOneVideoCall() : ZegoUIKitPrebuiltCallConfig.oneOnOneVoiceCall()
//        }
//        let config = ZegoUIKitPrebuiltCallInvitationService.shared.delegate?.requireConfig(invitationData) ?? normalConfig
//        let callVC: ZegoUIKitPrebuiltCallVC = ZegoUIKitPrebuiltCallVC.init(invitationData, config: config)
//        callVC.modalPresentationStyle = .fullScreen
//        callVC.delegate = ZegoUIKitPrebuiltCallInvitationService.shared.help
//        currentViewController()?.present(callVC, animated: true, completion: nil)
//        ZegoCallInvitationDialog.hide()
//        ZegoUIKitPrebuiltCallInvitationService.shared.callVC = callVC
//        ZegoUIKitPrebuiltCallInvitationService.shared.delegate?.onIncomingCallAcceptButtonPressed?()
//        ZegoCallAudioPlayerTool.stopPlay()
//        ZegoUIKitPrebuiltCallInvitationService.shared.state = .accept
////        ZegoUIKitPrebuiltCallInvitationService.shared.invitationData = nil
//
//    }
//}
//
//extension ZegoCallInvitationDialog: ZegoRefuseInvitationButtonDelegate {
//    func onRefuseInvitationButtonClick() {
//        ZegoCallAudioPlayerTool.stopPlay()
//        ZegoUIKitPrebuiltCallInvitationService.shared.delegate?.onIncomingCallDeclineButtonPressed?()
//        ZegoUIKitPrebuiltCallInvitationService.shared.invitationData = nil
//        ZegoUIKitPrebuiltCallInvitationService.shared.callID = nil
//        ZegoCallInvitationDialog.hide()
//        ZegoUIKitPrebuiltCallInvitationService.shared.state = .normal
//    }
//}
